package com.lkd.http.controller;

import cn.hutool.core.util.ObjectUtil;
import com.lkd.entity.SkuEntity;
import com.lkd.exception.LogicException;
import com.lkd.file.FileManager;
import com.lkd.service.SkuService;
import com.lkd.vo.Pager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/sku")
@Slf4j
public class SkuController {

    @Autowired
    private SkuService skuService;

    @Autowired
    private FileManager fileManager;

    /*
    * 商品分页
    * */
    @GetMapping("/search")
    public Pager<SkuEntity> search(
            @RequestParam(defaultValue = "1") Integer pageIndex,
            @RequestParam(defaultValue = "10") Integer pageSize,
            String skuName,
            Long classId){//1.接收参数
        //2. 调用并返回
        return skuService.search(pageIndex,pageSize,skuName,classId);
    }


    /*
    * 文件上传
    * */
   @PostMapping("/fileUpload")
   public String fileUpload(MultipartFile fileName){//1. 接收文件对象
       //2.校验
       if(ObjectUtil.isEmpty(fileName)){
           throw new LogicException("请上传有效文件");
       }
       //3.文件上传
       String filePath = fileManager.uploadFile(fileName);
       //4.返回地址
       return filePath;
   }

    /*
    * 商品新增
    * */
   @PostMapping
   public Boolean saveSku(@RequestBody SkuEntity skuEntity){
       //省略校验代码
       return skuService.save(skuEntity);
   }

    /*
    * 商品修改
    * */
    @PutMapping("/{skuId}")
    public Boolean updateSku(@PathVariable("skuId") Long skuId,@RequestBody SkuEntity skuEntity){
        //关连商品id
        skuEntity.setSkuId(skuId);
        //省略校验代码
        //调用service修改
        return skuService.updateById(skuEntity);
    }


}